package com.zidongxiangxi.rabbit.starter.manager;

import com.zidongxiangxi.rabbit.core.job.AbstractDaemonWorkThread;
import com.zidongxiangxi.rabbit.core.job.AbstractWorkThread;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.util.CollectionUtils;

import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.Objects;

/**
 * 工作线程管理类
 *
 * @author chenxudong
 * @date 2020/11/08
 */
public class WorkThreadManager implements ApplicationListener<ApplicationStartedEvent>, ApplicationContextAware {
	private final AbstractDaemonWorkThread daemonWorkThread;

	private ApplicationContext applicationContext;

	public WorkThreadManager(AbstractDaemonWorkThread daemonWorkThread) {
		this.daemonWorkThread = daemonWorkThread;
	}

	@Override
	public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
		if (Objects.nonNull(daemonWorkThread)) {
			Map<String, AbstractWorkThread> workThreadMap = applicationContext.getBeansOfType(AbstractWorkThread.class);
			if (CollectionUtils.isEmpty(workThreadMap)) {
				return;
			}
			daemonWorkThread.setDaemon(true);
			daemonWorkThread.addWorkThread(workThreadMap.values());
			daemonWorkThread.start();
		}
	}

	@PreDestroy
	public void preDestroy() {
		if (Objects.nonNull(daemonWorkThread)) {
			daemonWorkThread.stopWorking();
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
